<template>
  <div>
    <table>
      <thead>
        <tr>
          <th>ID</th>
          <th>Name</th>
          <th>Age</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="user in users" :key="user.id">
          <td>{{ user.id }}</td>
          <td>{{ user.name }}</td>
          <td>{{ user.age }}</td>
        </tr>
      </tbody>
    </table>
    <div v-if="isLoading">加载中...</div>
  </div>
</template>
 
<script>
import { ref,onUnmounted} from 'vue';
 
export default {
  setup() {
    const users = ref([{ id: 1, name: 'Alice', age: 30 }]); // 初始数据
    const isLoading = ref(false);
 
    const loadMoreData = () => {
      // 模拟异步获取数据
      setTimeout(() => {
        users.value.push({ id: users.value.length + 1, name: 'User', age: 25 });
      }, 1000);
    };
 
    const handleScroll = () => {
      const { scrollTop, scrollHeight, clientHeight, scrollLeft, scrollWidth, clientWidth } = document.documentElement;
      const nearBottom = scrollHeight - (clientHeight + scrollTop) < 10; // 距离底部10px时加载
      const nearRight = scrollWidth - (clientWidth + scrollLeft) < 10; // 距离右边10px时加载(如果需要)
 
      if (nearBottom && !isLoading.value) {
        isLoading.value = true;
        loadMoreData(); // 加载更多数据
        setTimeout(() => {
          isLoading.value = false;
        }, 1000);
      }
    };
 
    window.addEventListener('scroll', handleScroll);
 
    // 组件卸载前移除事件监听
    onUnmounted(() => {
      window.removeEventListener('scroll', handleScroll);
    });
 
    return { users, isLoading };
  },
};
</script>